'use strict';


const xlsx = require('node-xlsx') //导入Excel类库

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	const db = uniCloud.database();
	const _ = db.command

	let excelName = "用户体重数据"

	// 1. 定义excel表格名
	let dataCVS = 'test.xlsx'
	// 2. 定义存储数据的
	let alldata = [];
	// 3. 定义表头
	let row = ['日期', "时间", "日期时间", "体重"];

	// 取出集合记录总数
	const countResult = await db.collection("weight").where({
		openId: event.openid
	}).count()
	let count = countResult.total

	let all_data = []
	// 最多查询100次
	for (let i = 0; i < 100; i++) {
		// 查找数据
		let data = await db.collection("weight").aggregate()
			.match({
				openId: _.eq(event.openid)
			})
			.sort({
				dateTime: -1,
			})
			.skip(all_data.length)
			.limit(1000) // 限制返回数量为 10 条
			.end()

		all_data = all_data.concat(data.data)
		// 数据取出完成
		if (all_data.length >= count) {
			break
		}
	}



	let dataList = all_data


	alldata.push(row);
	// 4. 循环取出姓名数据
	for (let key in dataList) {
		let arr = [];
		arr.push(dataList[key].date);
		arr.push(dataList[key].time + ":00");
		arr.push(dataList[key].date + " " + dataList[key].time + ":00");
		arr.push(dataList[key].weight);
		alldata.push(arr)
	}
	//5. 把数据保存到excel里
	var buffer = await xlsx.build([{
		name: "用户体重数据",
		data: alldata
	}]);



	//6. 把excel文件保存到云存储里


	return await uniCloud.uploadFile({
		cloudPath: excelName + ".xlsx",
		fileContent: buffer
	});
	// console.log('res : ', res)




};
